package com.kefu.chat.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kefu.chat.mapper.ChatMenuConfigMapper;
import com.kefu.chat.mapper.ChatMenuConfigPlanMapper;
import com.kefu.chat.model.ChatMenuConfig;
import com.kefu.chat.model.ChatMenuConfigPlan;
import com.kefu.chat.vo.ChatMenuConfigSearchVo;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.common.util.Assert;
import com.kefu.common.util.JacksonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class ChatMenuConfigService extends AbstractKefuService<ChatMenuConfig> {
    @Resource
    private ChatMenuConfigMapper chatMenuConfigMapper;
    @Resource
    private ChatMenuConfigPlanMapper chatMenuConfigPlanMapper;
    public List<ChatMenuConfig> getAll(ChatMenuConfigSearchVo search) {
        return chatMenuConfigMapper.selectList(search.lambdaQuery());
    }

    @Override
    public void deleteById(String id) {
        Long count = chatMenuConfigPlanMapper.selectCount(Wrappers.lambdaQuery(ChatMenuConfigPlan.class)
                .like(ChatMenuConfigPlan::getMenus, id));
        Assert.isTrue(count > 0, "快捷菜单已经被引用，不能删除！");
        super.deleteById(id);
    }

    public void batchDelete(List<String> ids) {
        Assert.isTrue(CollUtil.isEmpty(ids), "未选择快捷菜单！");
        boolean flag = true;
        for (String id : ids) {
            Long count = chatMenuConfigPlanMapper.selectCount(Wrappers.lambdaQuery(ChatMenuConfigPlan.class)
                    .like(ChatMenuConfigPlan::getMenus, id));
            if (count > 0) {
                flag = false;
            }
        }
        Assert.isTrue(!flag, "快捷菜单已被使用，不能删除！");
        chatMenuConfigMapper.deleteBatchIds(ids);
        log.info("批量删除快捷菜单:{}", JacksonUtil.toString(ids));
    }
}
